package com.xh.shuati.ai;
import com.xh.shuati.utils.ImageUtils;
import dev.langchain4j.data.message.*;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
import static dev.langchain4j.internal.Utils.readBytes;

@Component
public class AiServiceVisualConfig {


    @Resource
    private ChatLanguageModel myQwenVLChatModel;

    @Resource
    private StreamingChatLanguageModel myQwenStreamingVLChatModel;

    @Resource
    private  AiService aiService;

    @Resource
    private ChatMemoryProvider mySqlBasedChatMemoryProvder;

    private static String systemPrompt;

    static {
        try (InputStream inputStream = AiServiceVisualConfig.class.getClassLoader().getResourceAsStream("system-prompt-vlchat.txt")) {
            if (inputStream == null) {
                throw new RuntimeException("system-prompt-vlchat.txt 文件未找到");
            }
            systemPrompt = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
                    .lines()
                    .collect(Collectors.joining("\n"));
        } catch (Exception e) {
            e.printStackTrace();
            systemPrompt = "";
        }
    }

    public String vlChat(Long memoryId, String query, String imagePath) {

        // 创建系统提示和用户消息
        SystemMessage systemMessage = SystemMessage.from(systemPrompt);
        ImageContent imageContent = ImageContent.from(imagePath);
        UserMessage userMessage = UserMessage.from(TextContent.from("请帮我解析个人简历"),
                imageContent);
        //调用vlchatmodel
        ChatResponse response = myQwenVLChatModel.chat(List.of(systemMessage, userMessage));

        AiMessage aiMessage = response.aiMessage();
        String resultText = aiMessage.text().trim();
        // 3. 判断结果是否为错误格式
        if (resultText.contains("\"error\"")) {
            // 简单粗暴的判断方式，最好用 JSON 解析判断 key 是否为 "error"
            System.out.println("识别失败： 该图像不是简历，检查输入简历的内容或路径是否正确");
            return resultText; // 或你希望返回的错误 JSON
        }

        //再调用chatmodel进行对话
        String answer = aiService.chat(memoryId, "下面是我个人简历的json格式\n"+resultText+"\n"+query);

        return answer;
    }

    public Flux<String> vlChatStream(Long memoryId, String query, String imagePath) {

        // 创建系统提示和用户消息
        SystemMessage systemMessage = SystemMessage.from(systemPrompt);
        ImageContent imageContent = ImageContent.from(imagePath);
        UserMessage userMessage = UserMessage.from(TextContent.from("请帮我解析个人简历"),
                imageContent);
        //调用vlchatmodel
        ChatResponse response = myQwenVLChatModel.chat(List.of(systemMessage, userMessage));

        AiMessage aiMessage = response.aiMessage();
        String resultText = aiMessage.text().trim();
        // 3. 判断结果是否为错误格式
        if (resultText.contains("\"error\"")) {
            // 简单粗暴的判断方式，最好用 JSON 解析判断 key 是否为 "error"
            System.out.println("识别失败： 该图像不是简历，检查输入简历的内容或路径是否正确");
            return Flux.just(resultText); // 或你希望返回的错误 JSON
        }

        //再调用chatmodel进行对话
        Flux<String> answer = aiService.chatStream(memoryId, "下面是我个人简历的json格式\n\n" + resultText + "\n\n接着根据我的提问继续回答\n" + query);

        return answer;
    }
}
